import 'dart:async';

import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/custom_event_bus.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/education_comment_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_text_book_setting_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/textbook_detail_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/train_plan/get_education_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///课程详情
class CourseDetailController extends GetxController {
  ///是否可以学习 默认不可学习
  bool isStudy = false;

  /// 创建一个全局的 ScrollController
  ScrollController myScrollController = ScrollController();

  /// 初始页面设置 [initPage] 0: 1：3
  int initPage = 0;

  /// 计划名字
  String? planName = '';
  String? startTime = '';
  String? endTime = '';

  ///很重要的id 不仅这里需要 还要传入到后面的的界面使用（列如：上传观看进度和总时长）
  String? planId = '';

  ///进度 %%%%%
  double progress = 0;

  ///index
  int index = 0;

  /// 查询课程详情
  TextbookDetailEntity? textbookDetailEntity;

  ///查询课程设置   和是否人脸识别了（isPersonIdentify）
  GetTextBookSettingEntity? getTextBookSettingEntity;
  StreamSubscription<MyEntity>? eventSubscription;

  ///评价数量
  RxString courseDetailEvaluateCount = '0'.obs;

  ///根据该课程的计划（根据当前课程查询计划 1对多）
  List<GetEducationPlanEntity>? getEducationPlanEntity;
  /// 计划id 计划名字
   List<GetDictAllEntity> programType = [];
  /// 进行人脸识别
  void confirm() {
    //这里判断下当没有目录的时候 提示用户敬请期待~
    if (!isStudy) {
      AppToast.showWarning('敬请期待~');
      return;
    }
    final bool isFace = _faceBool();
    if (isFace) {
      //直接进入详情
      Get.toNamed(AppRoutes.courseDetailDetailPage, arguments: {
        'id': Get.arguments['id'],
        'directoryFile': null,
        'planId': planId,
      });
      return;
    }
    Get.toNamed(AppRoutes.faceAuth, arguments: {
      'type': FaceAuthType.recog, // 识别类型
    })?.then((value) {
      // 从此页面返回，会返回一个 bool?
      // - true：成功
      // - false：失败
      // - null：未识别
      if (value == true) {
        Get.toNamed(AppRoutes.courseDetailDetailPage, arguments: {
          'id': Get.arguments['id'],
          'directoryFile': null,
          'planId': planId,
        });
      } else if (value == false) {
        AppToast.showWarning('人脸识别失败');
      } else {
        AppToast.showWarning('未识别');
      }
    });
  }

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments['isStudy'] != null) {
      isStudy = Get.arguments['isStudy'] as bool;
    }
    //查询课程详情
    textbookDetail();
    //查询课程设置(考试时长)
    getTextBookSetting();

    //根据该课程的计划（根据当前课程查询计划 1对多） /education//educationPlan/getPlanByTextbookId
    getPlanByTextbookId();
    //单单只获取评论数量
    getListComment();
    //接受事件
    eventSubscription = CustomEventBus.getInstance().on<MyEntity>().listen((event) {
      if (event.type == MyEntity.TYPECOURSEDETAILEVALUATECOUNT) {
        //处理评价数量事件
        courseDetailEvaluateCount.value = event.data as String;
      } else if (event.type == MyEntity.TYPGETPLANBYTEXTBOOKID) {
        getPlanByTextbookId();
      }
    });
  }
  ///查询课程详情
  void textbookDetail() async {
    final res = await HttpUtil().generateGetRequest<TextbookDetailEntity>(
      Interface.textbookDetail,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        textbookDetailEntity = result.data!;
        update();
      }
    });
  }

  /// 查询课程设置(考试时长)
  void getTextBookSetting() async {
    final res = await HttpUtil().generateGetRequest<GetTextBookSettingEntity>(
      Interface.getTextBookSetting,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getTextBookSettingEntity = result.data!;
      }
    });
  }

  /// 是否进行了人脸识别
  bool _faceBool() {
    if (getTextBookSettingEntity?.isPersonIdentify != null && getTextBookSettingEntity?.isPersonIdentify == 0) {
      //是否进行实人验证  //0：人脸识别
      return true;
    }
    return false;
  }

  @override
  void onClose() {
    super.onClose();
    //取消EventBus事件订阅，防止内存泄漏。
    eventSubscription?.cancel();
  }

  ///根据该课程的计划（根据当前课程查询计划 1对多）
  void getPlanByTextbookId() async {
    final res = await HttpUtil().generateGetRequest<List<GetEducationPlanEntity>>(
      Interface.getPlanByTextbookId,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        //1.没有数据就是隐藏改计划进度UI
        getEducationPlanEntity = result.data!;
        if (getEducationPlanEntity!.isNotEmpty) {
          planName = getEducationPlanEntity?[index].planName;
          startTime = getEducationPlanEntity?[index].startTime;
          endTime = getEducationPlanEntity?[index].endTime;
          planId = getEducationPlanEntity?[index].id;
          //查询课程的进度
          getCheckTheProgressOfLastViewing(planId);

          //2.有数据添加到选择里
         programType.clear();
          for (int i = 0; i < getEducationPlanEntity!.length; i++) {
            // 获取计划id 获取计划名字
            final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
            //获取计划id
            getDictAllEntity4.id = getEducationPlanEntity?[i].id;
            //获取计划名字
            getDictAllEntity4.dictionaryLabel = getEducationPlanEntity?[i].planName;
            getDictAllEntity4.dictionarySort = i;
            programType.add(getDictAllEntity4);
          }
        }
        update();
      }
    });
  }

  GetDictAllEntity? dictEntity;

  ///计划id 计划名字
  void selectProgramType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '计划',
      dataList: programType,
      checkedList: [dictEntity ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity = value[0];
        //计划id
        planId = value[0].getId();
        //计划名字
        planName = value[0].getShowName();
        //用户选中的角标
        index = value[0].dictionarySort ?? 0;
        //点击后刷新数据
        getPlanByTextbookId();
      },
    );
  }

  ///查询课程的进度
  void getCheckTheProgressOfLastViewing(String? planId) async {
    final res = await HttpUtil().generateGetRequest(
      Interface.checkTheProgressOfLastViewing,
      queryParameters: {
        'textbookId': Get.arguments['id'],
        'planId': planId, //计划id
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        progress = double.parse('${result.data}');
        update();
      }
    });
  }

  /// 获取 评论数量
  void getListComment() async {
    final res = await HttpUtil().generateGetRequest<List<EducationCommentListEntity>>(
      Interface.listComment,
      queryParameters: {
        'commentType': 0, //	类型 0：评价 1：问答
        'textbookId': Get.arguments['id'], //课程ID
      },
    ).execute();
    List<EducationCommentListEntity>? listComment = [];
    res.onSuccess((result) {
      if (result.data != null) {
        listComment = result.data;
        courseDetailEvaluateCount.value = '${listComment!.length}';
      }
    });
  }

  ///更多课程-往期回顾
  void moreCourses() {
    Get.toNamed(AppRoutes.previousReviewPage);
  }
}
